<template>
  <div class="login-container">
    <!-- 背景视频 -->
    <video 
      ref="backgroundVideo"
      class="background-video" 
      autoplay 
      muted 
      playsinline
      loop
      preload="auto"
      poster="/background.png"
    >
      <!-- MP4 格式作为主要视频源 -->
      <source src="/background-video.mp4" type="video/mp4">
      <!-- 降级：不支持视频的浏览器显示图片 -->
      <img src="/background.png" alt="登录背景">
    </video>
    
    <!-- 视频遮罩层 -->
    <div class="video-overlay"></div>
    
    <!-- 页面标题和副标题 -->
    <div class="page-header">
      <h1 class="main-title">灵感触发，AI 实现</h1>
      <p class="subtitle">连接想象与现实的桥梁</p>
    </div>
    
    <!-- 登录框 -->
    <div class="login-box">
      <div class="login-header">
        <!-- 登录框内不再显示标题 -->
      </div>

      <!-- 登录表单 -->
      <div class="form-container" v-show="!showRegister">
        <div class="form-group">
          <label>用户名</label>
          <input 
            v-model="loginForm.username" 
            type="text" 
            placeholder="请输入用户名"
            @keyup.enter="handleLogin"
          />
        </div>
        <div class="form-group">
          <label>密码</label>
          <input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          />
        </div>
        <button class="submit-btn" @click="handleLogin" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
        
        <!-- 注册引导区域 -->
        <div class="register-guide">
          <span>还没有账号？</span>
          <a href="#" @click.prevent="showRegisterForm">立即注册</a>
        </div>
      </div>

      <!-- 注册表单 -->
      <div class="form-container" v-show="showRegister">
        <div class="form-group">
          <label>用户名</label>
          <input 
            v-model="registerForm.username" 
            type="text" 
            placeholder="请输入用户名"
          />
        </div>
        <div class="form-group">
          <label>邮箱（可选）</label>
          <input 
            v-model="registerForm.email" 
            type="email" 
            placeholder="请输入邮箱"
          />
        </div>
        <div class="form-group">
          <label>密码</label>
          <input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码"
            @keyup.enter="handleRegister"
          />
        </div>
        <button class="submit-btn" @click="handleRegister" :disabled="loading">
          {{ loading ? '注册中...' : '注册' }}
        </button>
        
        <!-- 返回登录链接 -->
        <div class="register-guide">
          <span>已有账号？</span>
          <a href="#" @click.prevent="showRegister = false">立即登录</a>
        </div>
      </div>

      <!-- 消息提示 -->
      <div v-if="message" :class="['message', messageType]">
        {{ message }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { login, register } from '../api/auth'

const router = useRouter()
const backgroundVideo = ref<HTMLVideoElement | null>(null)

// 加载状态
const loading = ref(false)

// 登录表单
const loginForm = ref({
  username: '',
  password: ''
})

// 注册表单
const registerForm = ref({
  username: '',
  password: '',
  email: ''
})

// 控制注册表单显示
const showRegister = ref(false)

// 消息提示
const message = ref('')
const messageType = ref('success')

// 显示消息
const showMessage = (msg: string, type = 'success') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 预加载视频资源
const preloadVideo = () => {
  // 创建视频元素进行预加载
  const video = document.createElement('video');
  video.preload = 'auto';
  video.src = '/background-video.mp4';
  // 注意：不再预加载海报图片，避免与首页背景冲突
}

// 在组件挂载前预加载视频
onBeforeMount(() => {
  preloadVideo();
})

// 处理登录
const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    showMessage('请输入用户名和密码', 'error')
    return
  }

  loading.value = true
  console.log('开始登录，用户名:', loginForm.value.username)
  
  try {
    const response = await login(loginForm.value)
    const res = response.data
    console.log('登录响应完整数据:', response)
    console.log('登录成功，返回数据:', res)
    
    // 保存 JWT Token 和用户信息
    if (res.data.token) {
      localStorage.setItem('token', res.data.token)
      console.log('✅ JWT Token 已保存')
    }
    if (res.data.refresh) {
      localStorage.setItem('refresh_token', res.data.refresh)
      console.log('✅ Refresh Token 已保存')
    }
    localStorage.setItem('userInfo', JSON.stringify(res.data))
    
    showMessage(res.message || '登录成功', 'success')
    
    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      router.push('/home')
    }, 500)
  } catch (error: any) {
    console.error('登录失败，完整错误:', error)
    console.error('错误类型:', error.constructor.name)
    console.error('错误消息:', error.message)
    console.error('错误响应:', error.response)
    
    let errorMsg = '登录失败'
    if (error.response) {
      errorMsg = error.response.data?.message || error.message || '服务器错误'
    } else if (error.message) {
      errorMsg = error.message
    }
    
    showMessage(errorMsg, 'error')
  } finally {
    loading.value = false
  }
}

// 显示注册表单
const showRegisterForm = () => {
  showRegister.value = true
}

// 处理注册
const handleRegister = async () => {
  if (!registerForm.value.username || !registerForm.value.password) {
    showMessage('请输入用户名和密码', 'error')
    return
  }

  loading.value = true
  try {
    const response = await register(registerForm.value)
    const res = response.data
    console.log('注册成功:', res)
    
    // 保存 JWT Token 和用户信息
    if (res.data.token) {
      localStorage.setItem('token', res.data.token)
      console.log('✅ JWT Token 已保存')
    }
    if (res.data.refresh) {
      localStorage.setItem('refresh_token', res.data.refresh)
      console.log('✅ Refresh Token 已保存')
    }
    localStorage.setItem('userInfo', JSON.stringify(res.data))
    
    showMessage(res.message || '注册成功', 'success')
    
    // 延迟跳转
    setTimeout(() => {
      router.push('/home')
    }, 500)
  } catch (error: any) {
    console.error('注册失败:', error)
    let errorMsg = '注册失败'
    if (error.response) {
      errorMsg = error.response.data?.message || error.message || '服务器错误'
    } else if (error.message) {
      errorMsg = error.message
    }
    showMessage(errorMsg, 'error')
  } finally {
    loading.value = false
  }
}

// 视频无缝循环优化
onMounted(() => {
  // 页面加载完成后给body加loaded类
  document.body.classList.add('loaded');
  
  if (backgroundVideo.value) {
    // 实现更平滑的循环播放
    backgroundVideo.value.addEventListener('timeupdate', () => {
      if (backgroundVideo.value && backgroundVideo.value.duration) {
        // 在视频接近结束时重新开始，避免明显的停顿
        if (backgroundVideo.value.currentTime > backgroundVideo.value.duration - 0.2) {
          backgroundVideo.value.currentTime = 0;
        }
      }
    });
    
    // 添加错误处理
    backgroundVideo.value.addEventListener('error', (e) => {
      console.error('视频加载失败:', e);
      // 如果视频加载失败，确保页面仍然可以正常使用
      document.body.classList.add('loaded');
    });
  }
})
</script>

<style scoped>
.login-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  padding: 20px;
}

.background-video {
  position: fixed;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -2;
  transform: translate(-50%, -50%);
  object-fit: cover;
  filter: brightness(1.2) contrast(1.1); /* 增加亮度和对比度 */
  opacity: 0;         /* 初始透明，避免加载时的闪烁 */
  transition: opacity 0.3s ease;  /* 淡入过渡，掩盖黑屏 */
  background: url('/background.png') center/cover no-repeat; /* 添加背景图片防止黑屏 */
}

/* 页面加载完成后，视频淡入 */
body.loaded .background-video {
  opacity: 1;
}

.video-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4); /* 调整透明度，使背景更明亮 */
  z-index: -1;
}

/* 页面标题样式 */
.page-header {
  position: absolute;
  top: 15%;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  z-index: 1;
  width: 580px;
  max-width: 90%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.main-title {
  font-size: 36px;
  margin: 0 0 10px 0;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 24px;
  margin: 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-box {
  width: 100%;
  max-width: 580px;
  min-height: 320px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-top: 80px; /* 为顶部标题留出空间 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  color: white;
  margin: 0 0 10px 0;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.login-header p {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.login-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.1);
  padding: 5px;
}

.tab {
  flex: 1;
  padding: 15px;
  border: none;
  background: transparent;
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.tab.active {
  background: rgba(255, 255, 255, 0.3);
  color: white;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.tab:hover:not(.active) {
  background: rgba(255, 255, 255, 0.2);
}

.form-container {
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-size: 14px;
  color: white;
  margin-bottom: 8px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.form-group input {
  width: 100%;
  padding: 15px 20px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-group input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-group input:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.1);
}

.submit-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
  backdrop-filter: blur(5px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.message {
  margin-top: 20px;
  padding: 15px;
  border-radius: 10px;
  font-size: 14px;
  text-align: center;
  animation: slideIn 0.3s;
  backdrop-filter: blur(5px);
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.success {
  background: rgba(40, 167, 69, 0.2);
  color: #d4edda;
  border: 1px solid rgba(40, 167, 69, 0.3);
}

.message.error {
  background: rgba(220, 53, 69, 0.2);
  color: #f8d7da;
  border: 1px solid rgba(220, 53, 69, 0.3);
}

/* 注册引导区域样式 */
.register-guide {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.register-guide a {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  margin-left: 5px;
  transition: color 0.3s;
}

.register-guide a:hover {
  color: #764ba2;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    top: 10%;
  }
  
  .main-title {
    font-size: 28px;
  }
  
  .subtitle {
    font-size: 16px;
  }
  
  .login-box {
    padding: 30px 20px;
    margin-top: 100px;
  }
  
  .tab {
    padding: 12px;
    font-size: 14px;
  }
  
  .form-group input {
    padding: 12px 16px;
    font-size: 14px;
  }
  
  .submit-btn {
    padding: 14px;
  }
}
</style>
